package ie.nell;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.*;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.PopupWindow;
import android.widget.TextView;

public class UXBrowser extends Activity implements OnTouchListener, OnKeyListener {

    private WebView webView;
    private WebViewClient client;
    private TextView textView;
    private int clicks = 0;
    private EventDBOpenHelper dbh;
    private SQLiteDatabase db;
    private Cursor cursor;
    private int xOff;
    private int yOff;
    private int xDoc;
    private int yDoc;
    private int x;
    private int y;
    private String currentUrl = "";
    private int currentUrlId = 0;
    private Intent userCreationIntent;
    private PopupWindow pw;
    private UXBrowser uxb;
    private ApplicationSettings as;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
        setContentView(R.layout.main);
        final Activity UXBActivity = this;
        as = new ApplicationSettings(this);
        dbh = new EventDBOpenHelper(this.getApplicationContext());
        ApplicationSettings.dbh = dbh;
        db = dbh.getWritableDatabase();
        ApplicationSettings.db = db;

        // WebView
        webView = (WebView) findViewById(R.id.webview);
        webView.setOnTouchListener(this);
        webView.setOnKeyListener(this);
        webView.setPictureListener(new ScreenshotListener());
        webView.enablePlatformNotifications();

        // Progressbar

        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int progress) {
                UXBActivity.setProgress(progress * 100);
                if (progress == 100) {
                    UXBActivity.setTitle(R.string.app_name);
                }
            }
        });
        client = new UXWebViewClient(this);
        webView.setWebViewClient(client);
        webView.setVerticalScrollBarEnabled(false);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.clearCache(true);
        webView.loadUrl("http://www.ncirl.ie");

        // status window
        textView = (TextView) findViewById(R.id.textview);
        textView.setOnKeyListener(this);
        uxb = this;


    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.webview && event.getAction() == MotionEvent.ACTION_DOWN && ApplicationSettings.isRecordClick()) {
            xOff = webView.getScrollX();
            yOff = webView.getScrollY();
            x = (int) event.getX();
            y = (int) event.getY();
            xDoc = xOff + x;
            yDoc = yOff + y;
            textView.setText("Click: " + x + "/" + y + ", " + xDoc + "/" + yDoc);
            ContentValues values = new ContentValues();
            values.put("type", 1);
            values.put("x", x);
            values.put("y", y);
            values.put("x_doc", xDoc);
            values.put("y_doc", yDoc);
            values.put("url", currentUrlId);
            db.insert(EventDBOpenHelper.EVENT_TABLE_NAME, "0", values);
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        textView.setText("onKeyDown");
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (pw != null) {
                pw.dismiss();
            }
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    public boolean onKey(View arg0, int arg1, KeyEvent evt) {
        int keycode = evt.getKeyCode();
        if (keycode == KeyEvent.KEYCODE_PLUS) {
            webView.getSettings().setDefaultZoom(ZoomDensity.CLOSE);
            textView.setText("Scale: " + webView.getScale());
            return true;
        }
        if (keycode == KeyEvent.KEYCODE_MINUS) {
            webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
            textView.setText("Scale: " + webView.getScale());
            return true;
        }
        if (keycode == KeyEvent.KEYCODE_EQUALS) {
            webView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);
            textView.setText("Scale: " + webView.getScale());
            return true;
        }
        return false;
    }

    public void recordURL(String url) {
        currentUrlId = 1;
        ContentValues values = new ContentValues();
        values.put("url", url);
        values.put("type", "url");
        db.insert(EventDBOpenHelper.URL_TABLE_NAME, "0", values);
        cursor = db.query(EventDBOpenHelper.URL_TABLE_NAME, new String[]{EventDBOpenHelper.URL_ID},
                "url='" + url + "'", null, null, null, null);
        if (cursor != null && cursor.moveToNext()) {
            currentUrlId = cursor.getInt(0);
        }
        textView.setText("new URL: " + url + " ID: " + currentUrlId);
    }

    public void recordTitle(String title) {
        ContentValues values = new ContentValues();
        values.put("url", currentUrl);
        values.put("type", "title");
        db.insert(EventDBOpenHelper.URL_TABLE_NAME, "0", values);
        textView.setText("new title: " + title);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.reload_option:
                webView.loadUrl(webView.getUrl());
                break;
            case R.id.stats_option:
                userCreationIntent = new Intent(this.getApplicationContext(), Stats.class);
                startActivityForResult(userCreationIntent, 0);
                break;
            case R.id.settings_option:
                userCreationIntent = new Intent(this.getApplicationContext(), Settings.class);
                startActivityForResult(userCreationIntent, 0);
                break;
            case R.id.about_option:
                showAbout();
                break;
            case R.id.exit_option:
                exitDialog();
                break;
        }
        return true;
    }

    private void exitDialog() {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.exit).setMessage(R.string.quit).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                //Stop the activity
                UXBrowser.this.finish();
            }
        }).setNegativeButton(R.string.no, null).show();

    }

    private void showAbout() {

        AlertDialog.Builder aboutDialog = new AlertDialog.Builder(UXBrowser.this);
        aboutDialog.setTitle(R.string.app_name);

        LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.about, null);

        aboutDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
            }
        });
        aboutDialog.setView(view);
        aboutDialog.show();


    }
}
